<template>
  <div id="app">
    <h1>{{ msg }}</h1>

    <h3>生产永久URL</h3>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="桶名">
        <el-input v-model="bucketName" placeholder="桶名"></el-input>
      </el-form-item>
      <el-form-item label="对象名称">
        <el-input v-model="objectName" placeholder="对象名称"></el-input>
      </el-form-item>
    </el-form>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="HTTP方法">
        <el-input v-model="HTTPMethod" placeholder="PUT POST GET DELETE"></el-input>
      </el-form-item>
      <el-form-item label="永久 URL">
        <el-input v-model="URL" placeholder="URL"></el-input>
      </el-form-item>
      <el-form-item label="支持 GET POST PUT DELETE 操作对象">
      </el-form-item>
    </el-form>

    <p></p>

    <el-button type="primary" @click="submit0()">生成永久URL 预览(下载)/更新(上传)/删除 使用</el-button>
    <p></p>

    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="上传字符串">
        <el-input v-model="objectContent" placeholder="objectContent"></el-input>
      </el-form-item>
      <el-form-item label="PUT 永久URL">
        <el-input v-model="URL" placeholder="URL"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submit2()">上传字符串类型对象</el-button>
    </el-form>
    <p></p>


    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="上传file">
        <input type="file" v-on:change="onChange($event)"/>
      </el-form-item>
      <el-form-item label="PUT 永久URL">
        <el-input v-model="URL" placeholder="URL"></el-input>
      </el-form-item>
      <el-button type="primary" @click="submit3()">上传文件对象</el-button>
    </el-form>

    <p>{{data}}</p>

  </div>
</template>

<script>

  var OSS = require("oss-js-client");

  var ossClient = new OSS.Client({
    // endPoint: "192.168.1.40",
    endPoint: "127.0.0.1",
    port: 9000,
    useSSL: false,
    accessKey: "username",
    secretKey: "password",
  });

  //base64转bolb
  function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(',');
    //注意base64的最后面中括号和引号是不转译的
    var _arr = arr[1].substring(0, arr[1].length - 2);
    var mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(_arr),
      n = bstr.length,
      u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
      type: mime
    });
  };

  //将字符串转化为二进制的数据
  function strToBinary(str) {
    var result = [];
    var list = str.split("");
    for (var i = 0; i < list.length; i++) {
      if (i != 0) {
        //加空格，分割二进制
        result.push(" ");
      }
      var item = list[i];
      //将字符串转化为二进制数据
      var binaryStr = item.charCodeAt().toString(2);
      result.push(binaryStr);
    }
    return result.join("");
  }

  export default {
    name: "VueOSSObject",
    data() {
      return {
        bucketName: "mybucket2",
        objectName: "a.txt",
        objectContent: "a-Content",
        HTTPMethod: "GET",  //GET PUT POST
        URL: "",
        file: {},
        fileFormData: null,
        formInline: {},
        data: '',
        msg: "演示OSSClient-Object URL操作",
      };
    },
    methods: {
      onChange: function (event) {
        this.file = event.target.files[0]; // get input file object
        console.log(this.file);
      },

      //GET 永久URL
      submit0: function () {
        //URL支持 GET DELETE POST PUT 操作公开桶对象
        //浏览器/移动客户端可能会指向此URL，以将对象直接预览/下载/上传/更新等操作（桶策略必须是可读/可写的）
        ossClient.getObjectUrl(this.bucketName, this.objectName, (err, url) => {
          if (err) {
            this.data = err
            return console.log(err);
          } else {
            console.log(url);
            this.URL = url;
            this.data = url
          }
        });
      },

      //永久URL PUT请求  上传string对象
      //用于上传和更新对象 存储桶必须是公开的
      submit2: function () {
        let metaData = {
          'Content-Type': "text/plain",
        };

        //推荐 使用fetch发送请求
        fetch(this.URL, {
          method: 'PUT',
          body: this.objectContent,
          headers: metaData
        })
          .then(response => response)
          .catch(error => console.error('Error:', error))
          .then(response => console.log('Success:', response));
      },

      //永久URL PUT请求  上传file对象
      submit3: function () {
        let size = this.file.size;
        if (size < 0) {
          throw new InvalidArgumentError(`size cannot be negative, given size: ${size}`)
        }

        let metaData = {
          'Content-Type': this.file.type,
          "content-length": size
        };

        // eslint-disable-next-line no-undef
        let reader = new FileReader();
        reader.readAsDataURL(this.file);
        reader.onload = e => {
          const dataUrl = e.target.result;
          //base64转bolb
          const blob = dataURLtoBlob(dataUrl);
          //bolb转arrayBuffer
          // eslint-disable-next-line no-undef
          let reader2 = new FileReader();
          reader2.readAsArrayBuffer(blob, 'utf8');  // utf8 解决 zip文件下载后无法解压损坏问题
          reader2.onload = ex => {
            var binary = ex.target.result;
            // const ossBuffer = require('buffer').Buffer;
            //var buffer = ossBuffer(binary);
            // const buffer = Buffer.from(ex.target.result, 'base64');
            /*const stream = require('stream');
            var bufferStream = new stream.PassThrough();
            bufferStream.end(buffer);*/

            //推荐 使用fetch发送请求
            //根据签名URL 上传对象(binary对象类型)
            fetch(this.URL, {
              method: 'PUT',
              // body: buffer,
              // body: bufferStream,
              body: binary,
              headers: metaData
            })
              .then(response => response)
              .catch(error => console.error('Error:', error))
              .then(response => console.log('Success:', response));
          };
        }
      },

    }
  };
</script>

<style scope>
</style>
